package org.elsfs.cloud.common.mybatis.injector.methods;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.defaults.RawSqlSource;

/**
 * 根据ID判断是否存在记录
 *

 */
public class ExistsById extends AbstractMethod {

    /**
     * SQL脚本
     */
    private static final String SQL_SCRIPT = "SELECT 1 FROM %s WHERE %s=#{%s} %s LIMIT 1\n";

    /**
     * @see AbstractMethod#AbstractMethod(String)
     * @since 3.5.0
     */
    public ExistsById() {
        super("existsById");
    }

    /**
     * 注入自定义 MappedStatement
     *
     * @param mapperClass mapper 接口
     * @param modelClass  mapper 泛型
     * @param tableInfo   数据库表反射信息
     * @return MappedStatement
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = String.format(
            SQL_SCRIPT,
            tableInfo.getTableName(),
            tableInfo.getKeyColumn(),
            tableInfo.getKeyProperty(),
            tableInfo.getLogicDeleteSql(true, true)
        );

        SqlSource sqlSource = new RawSqlSource(configuration, sql, Object.class);
        return this.addSelectMappedStatementForOther(mapperClass, this.methodName, sqlSource, Boolean.class);
    }
}
